import { combineReducers } from 'redux'

import user from './user'
import counter from './counter'
import { Model } from './data'

const cvtModelToReducer = (model: Model) => {
  const actions = model.actions
  Object.keys(actions).forEach((key) => {
    actions[`${model.namespace}/${key}`] = actions[key]
    delete actions[key]
  })

  return (state = model.state, { type, ...payload }) => {
    const acInModel = model.actions[type]
    if (acInModel == null) {
      return state
    }

    return acInModel(state, payload)
  }
}

const cvtModelsToReducers = (models: { [key: string]: Model }) => {
  const reducers = {}
  Object.keys(models).forEach((key) => {
    reducers[key] = cvtModelToReducer(models[key])
  })
  return reducers
}

export default combineReducers(cvtModelsToReducers({ user, counter }))
